package ${package}.${rootArtifactId}.common.exception.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.net.URI;

/**
 * RestTemplate自定义异常处理
 *
 * @author weidong.lin
 * @date 2021/7/8 11:06
 */
public class RestTemplateExceptionHandler implements ResponseErrorHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateExceptionHandler.class);

    @Override
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        return clientHttpResponse.getStatusCode().value() != 200;
    }

    @Override
    public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

    }

    @Override
    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        LOGGER.error("============================RestTemplate Error============================");
        LOGGER.error("请求地址：{}", url.getHost() + url.getPath());
        LOGGER.error("请求方式：{}", method.name());
        LOGGER.error("请求异常：{}", response.getStatusCode());
        LOGGER.error("==========================================================================");
    }
}
